import { defineEventHandler, createError } from 'h3'
import type { H3Event } from 'h3'
import redis from '../../util/redis'

export default defineEventHandler(async (event: H3Event) => {
  const key = (event.context.params && event.context.params.key) || (event.node.req.url && event.node.req.url.split('/').pop())
  if (!key) throw createError({ statusCode: 400, statusMessage: 'missing key' })

  const client: any = redis
  const fullKey = 'shortlink:' + key
  const val = await client.get(fullKey)
  if (!val) throw createError({ statusCode: 404, statusMessage: 'not found' })

  // Try get TTL to report expire time (TTL returns seconds)
  let ttl = null
  try {
    const t = await client.ttl(fullKey)
    // Redis returns -1 for no expire, -2 for missing key
    if (typeof t === 'number') {
      if (t >= 0) ttl = t
      else ttl = null
    }
  } catch (e) {
    ttl = null
  }

  const resp: any = { url: val }
  resp.expireAt = ttl && ttl > 0 ? Date.now() + ttl * 1000 : null
  return resp
})
